<?php
/**
 * This file is part of the Agora distribution. 
 * Detailed copyright and licensing information can be found
 * in the gpl-3.0.txt file which should be included in the distribution.
 * 
 * @version		$Id: 3.0.14 Olympus 2010-09-28 rammstein4o $
 * @copyright  2007 - 2010 jVitals
 * @license   GPLv3 Open Source
 * @link       http://jvitals.com
 * @since      File available since initial release
 */
defined ('IN_AGORA') or die;
jimport('joomla.filesystem.folder');
jimport('joomla.filesystem.file');
class TaskController extends AgoraProfileController
{
    function _default()
    {

        $style = $this->agora_config['o_default_style'];

        $document = & JFactory::getDocument ();


        $user_helper = &$this->helper('user');

        $this->user = $user_helper->prepareUserTitle($this->user);

        $gallery_path =  DS. 'components'.DS.'com_agora'.DS.'img'.DS.'members'.DS.$this->user['id'];

        $files = $this->getFilesystemFilesFromFolder('components'.DS.'com_agora'.DS.'img'.DS.'members'.DS.$this->user['id'], $this->toShow());

        $this->view->assign('gallery_path',$gallery_path);

        $this->view->assign('files',$files);

        $this->view->assign('style',$style);
		
		$user_id = JRequest::getVar('user_id', '', 'get' );
		if ((int)$user_id) $this->view->assign('user_id',(int)$user_id);

        //~ $document->addStyleSheet(JURI::base () . 'components' .DS. 'com_agora' .DS. 'style' .DS. $style .DS. 'js_css' .DS. 'jquery.tablesorter.pager.css');

        //~ $document->addStyleSheet(JURI::base () . 'components' .DS. 'com_agora' .DS. 'style' .DS. $style .DS. 'js_css' .DS. 'jquery.tablesorter.css');

        //~ $document->addScript(JURI::base () . 'components' .DS. 'com_agora' .DS. 'js' .DS. 'jquery.tablesorter.min.js');

        //~ $document->addScript(JURI::base () . 'components' .DS. 'com_agora' .DS. 'js' .DS. 'jquery.tablesorter.pager.js');

        //~ $document->addScriptDeclaration('$j(function() {$j("table") .tablesorter({widthFixed: false}) .tablesorterPager({container: $j("#ag_pager")});});');



    }
    function toShow()
    {
        $ret = false;

        $my = & JFactory::getUser();


        if ($this->user['username']== $my->username){

            $ret = true;

        }else{

            $ret= false;

        }



        return $ret;

    }
    function getFilesystemFilesFromFolder($folder, $show=true) {
        $files = array();
		$mimetypes = array('jpg', 'jpeg', 'png', 'gif');
		$show = true;
        if (JFolder::exists(JPATH_BASE.DS.$folder)) {
            $fileList = JFolder::files(JPATH_BASE.DS.$folder);
            if (count($fileList) > 0) {
                $num=0;
                foreach($fileList as $file) {
                    if (strpos(strtolower($file), 'mini') === false){
                        if ($show==true){
                            //~ if ( strtolower(JFile::getExt($file)) <> 'jpg' && strtolower(JFile::getExt($file)) <> 'png' && strtolower(JFile::getExt($file)) <>'gif') {
							if (in_array(strtolower(JFile::getExt($file)), $mimetypes)) {
                                $files[$num]->name = strtoupper(JFile::stripExt($file));
                                $files[$num]->ext = strtoupper(JFile::getExt($file));
                                $files[$num]->link = JFile::stripExt($file).'.'.JFile::getExt($file);

                            }
                        }else{
                            if (!strstr(strtolower($file), 'hide')){
                                //~ if ( strtolower(JFile::getExt($file)) <> 'jpg' && strtolower(JFile::getExt($file)) <> 'png' && strtolower(JFile::getExt($file)) <>'gif') {
                                if (in_array(strtolower(JFile::getExt($file)), $mimetypes)) {
                                    $files[$num]->name = strtoupper(JFile::stripExt($file));
                                    $files[$num]->ext = strtoupper(JFile::getExt($file));
                                    $files[$num]->link = JFile::stripExt($file).'.'.JFile::getExt($file);

                                }
                            }
                        }

                        $num= $num+1;

                    }
                }
            }
        }
	
    return $files;

}

function download() {


    global $mainframe;

    $file_post = JRequest::getVar('file', '', 'get' );

    $file->name = $file_post;

    $file->path =  DS. 'components'.DS.'com_agora'.DS.'img'.DS.'members'.DS.$this->user['id'].DS.$file->name;

    if (!JFile::exists(JPATH_BASE.$file->path))
    {
        JError::raiseError (500, "ERROR FILE NOT FOUND");
        exit;
    }



    session_cache_limiter('public');

    // to avoid an error notice of an undefined index.
    if(empty($_SERVER['HTTP_REFERER'])) $_SERVER['HTTP_REFERER']='NoRef';
    if(empty($_SERVER['REMOTE_ADDR'])) $_SERVER['REMOTE_ADDR']='1.1.1.1';

    // Clean them variables boys  (always clean variables at the start of your script to prevent injection attacks. Always limit input to expected chars and patterns.)
    if(preg_match('/^([A-Za-z0-9.?=_\-\/:\s(%20)]{1,255})$/', stripslashes($_SERVER['HTTP_REFERER']), $matchref))
    {
        $tempvar = $matchref[0];
    } else {
        $tempvar='NoRef';
    }
    define('HTTP_REF', $tempvar);

    if(preg_match('/^([0-9.]{7,24})$/', stripslashes($_SERVER['REMOTE_ADDR']), $matchadd))
    {
        $tempvar = $matchadd[0];
    } else {
        $tempvar='1.1.1.1';
    }

    // required for IE, otherwise Content-disposition is ignored
    if(ini_get('zlib.output_compression'))
    ini_set('zlib.output_compression', 'Off');

    if( $file->name == "" )
    {
        JError::raiseError (500, "File name not specified");
    } else {
        $filename = JPATH_BASE.$file->path;
        if (!JFile::exists($filename))
        {
            JError::raiseError (500, "Oops. File not found".$filename);
            exit;
        }
    }

    session_write_close();

    //IE Bug in download name workaround
    if(isset($_SERVER['HTTP_USER_AGENT']) && preg_match('/MSIE/', $_SERVER['HTTP_USER_AGENT'])) {
        @ini_set( 'zlib.output_compression','Off' );
    }

    if (!$this->downloadFile($filename)) {
        JError::raiseError('', 'The file transfer failed');
    }

    die(); //if you do not

}

function downloadFile($fil,$p=null)
{
    // only show errors and remove warnings from corrupting file
    error_reporting(E_ERROR);

    ob_clean();
    if (connection_status()!=0) return(FALSE);

    $fn = basename($fil);
    header("Cache-Control: no-store, no-cache, must-revalidate");
    header("Cache-Control: post-check=0, pre-check=0", false);
    header("Pragma: no-cache");
    header("Expires: ".gmdate("D, d M Y H:i:s", mktime(date("H")+2, date("i"), date("s"), date("m"), date("d"), date("Y")))." GMT");
    header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
    header("Content-Transfer-Encoding: binary");

    //TODO:  Not sure of this is working
    if (function_exists('mime_content_type')) {
        $ctype = mime_content_type($fil);
    }
    else if (function_exists('finfo_file')) {
        $finfo    = finfo_open(FILEINFO_MIME);
        $ctype = finfo_file($finfo, $fil);
        finfo_close($finfo);
    }
    else {
        $ctype = "application/octet-stream";
    }

    header('Content-Type: ' . $ctype);

    if (strstr($_SERVER['HTTP_USER_AGENT'], "MSIE"))
    {
        //workaround for IE filename bug with multiple periods / multiple dots in filename
        //that adds square brackets to filename - eg. setup.abc.exe becomes setup[1].abc.exe
        $iefilename = preg_replace('/\./', '%2e', $fn, substr_count($fn, '.') - 1);
        header("Content-Disposition: attachment; filename=\"$iefilename\"");
    }
    else
    {
        header("Content-Disposition: attachment; filename=\"$fn\"");
    }

    header("Accept-Ranges: bytes");

    $range = 0; // default to begining of file
    //TODO make the download speed configurable
    $size=filesize($fil);

    //check if http_range is set. If so, change the range of the download to complete.
    if(isset($_SERVER['HTTP_RANGE']))
    {
        list($a, $range)=explode("=",$_SERVER['HTTP_RANGE']);
        str_replace($range, "-", $range);
        $size2=$size-1;
        $new_length=$size-$range;
        header("HTTP/1.1 206 Partial Content");
        header("Content-Length: $new_length");
        header("Content-Range: bytes $range$size2/$size");
    }
    else
    {
        $size2=$size-1;
        header("HTTP/1.0 200 OK");
        header("Content-Range: bytes 0-$size2/$size");
        header("Content-Length: ".$size);
    }

    //check to ensure it is not an empty file so the feof does not get stuck in an infinte loop.
    if ($size == 0 ) {
        JError::raiseError (500, 'ERROR.ZERO_BYE_FILE');
        exit;
    }
    set_magic_quotes_runtime(0); // in case someone has magic quotes on. Which they shouldn't as good practice.

    // we should check to ensure the file really exits to ensure feof does not get stuck in an infite loop, but we do so earlier on, so no need here.
    $fp=fopen("$fil","rb");

    //go to the start of missing part of the file
    fseek($fp,$range);
    if (function_exists("set_time_limit"))
    set_time_limit(0);
    while(!feof($fp) && connection_status() == 0)
    {
        //reset time limit for big files
        if (function_exists("set_time_limit"))
        set_time_limit(0);
        print(fread($fp,1024*8));
        flush();
        ob_flush();
    }
    sleep(1);
    fclose($fp);
    return((connection_status()==0) and !connection_aborted());
}



}
?>

